<?php

namespace app\service;

use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use think\facade\Log;

class AggregationService
{
	private string   $apiKey;
	private string   $domain;
	protected Client $client;

	private array $requestOrderListParams;

	private static ?AggregationService $instance = null;

	const ORDER_LIST = '/union/orders';

	private function __construct()
	{
		$this->apiKey = config('app.aggregation.api_key');
		$this->domain = config('app.aggregation.domain');

		$this->client = new Client([
			'base_uri' => $this->domain,
			'timeout'  => 3600,
		]);

		$this->requestOrderListParams = [
			'apikey' => $this->apiKey,
		];
	}

	public static function getInstance(): AggregationService
	{
		if (!self::$instance instanceof self) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * @throws GuzzleException
	 * @throws Exception
	 */
	public function getOrderList(): array
	{
		// 获取订单列表URL
		$requestData = [
			'headers' => $this->getHeaders(),
			'json'    => $this->requestOrderListParams,
		];

		$response = $this->client->post(self::ORDER_LIST, $requestData);
		$result   = json_decode($response->getBody(), true);
		
		if ($result['code'] != 1) {
			if ($result['msg'] != "【对应条件内无数据】") {
				Log::error(['getOrderList-requestData', $requestData]);
				Log::error(['getOrderList-responseData', $result]);
			}
			throw new Exception('获取订单列表失败：' . $result['msg']);
		}

		return $result['data'];
	}

	private function getHeaders(): array
	{
		return [
			'Content-Type' => 'application/json',
			'Accept'       => 'application/json',
		];
	}

	public function initStartEndTime($startTime, $endTime): void
	{
		$this->requestOrderListParams['start_time'] = $startTime;
		$this->requestOrderListParams['end_time']   = $endTime;
	}

	public function initRequestParams($params): void
	{
		foreach ($params as $index => $item) {
			$this->requestOrderListParams[$index] = $item;
		}
	}
}
